<?php

namespace Modules\File\Models;

use Core\Mvc\Collection;

class File extends Collection
{
    public $name;
    public $dir;
    public $md5;
    public $uid;
    public $extension;
    public $created;
    public $changed;
    public $access;

    public function beforeValidationOnCreate()
    {
        $user = $this->getDI()->getShared('user');
        if ($user->isLogin()) {
            $this->uid = $user->getUid();
        } else {
            $this->uid = null;
        }
        if ($this->created && !$this->changed) {
            $this->changed = $this->created;
        }
        if (!$this->created) {
            $this->created = $this->changed = intval(time());
        }
    }

    public function beforeSave()
    {
        $fileInfo = pathinfo($this->name);
        $this->extension = $fileInfo['extension'];
    }

    public function beforeValidationOnUpdate()
    {
        if (!$this->changed) {
            $this->changed = intval(time());
        }
    }

    public function isImages()
    {
        $imagesType = [
            'png' => 'png',
            'jpg' => 'jpg',
            'jepg' => 'jepg',
            'gif' => 'gif',
        ];
        if (isset($imagesType[strtolower($this->extension)])) {
            return true;
        }
        return false;
    }

    public function getUrl()
    {
        if ($this->access < 20) {
            return $this->getDI()->getShared('url')->get(['for' => 'privateFile', 'id' => $this->getId()]);
        }
        return '/' . $this->dir . $this->name;
        //return false;
    }

    public function getPath()
    {
        if ($this->access < 20) {
            return $this->dir . $this->name;
        }
        return WEB_CODE . '/' . $this->dir . $this->name;
        //return false;
    }
}
